/**
 * 
 */
package name.webdizz.gadget.four.envelope.client.view.widgets;

import name.webdizz.gadget.four.envelope.client.domain.Goal;
import name.webdizz.gadget.four.envelope.client.event.CreditGoalEventHandler;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Izzet_Mustafayev
 * 
 */
public class GoalItemUi extends BaseExpenseListItemUi {

	private static GoalItemUiBinder uiBinder = GWT
			.create(GoalItemUiBinder.class);

	@UiTemplate("ExpenseItemUi.ui.xml")
	interface GoalItemUiBinder extends UiBinder<Widget, GoalItemUi> {
	}

	private CreditGoalEventHandler creditGoalEventHandler;

	public GoalItemUi(final Goal expenseItem) {
		initWidget(uiBinder.createAndBindUi(this));
		init(expenseItem);
		// hide input when it loses focus
		assignExpenseValueChangeHandler();
	}

	/**
	 * 
	 */
	@Override
	protected void assignExpenseValueChangeHandler() {
		expenseValueEdit.addBlurHandler(new BlurHandler() {
			public void onBlur(final BlurEvent event) {
				expenseValueEdit.setVisible(false);
				String previousValue = expenseValue.getInnerText();
				expenseValue.setInnerText(expenseValueEdit.getValue());
				if (!previousValue.trim().equals(expenseValueEdit.getValue())) {
					expenseItem.setActual(Double.valueOf(expenseValueEdit
							.getValue()));
					creditGoalEventHandler.onSave((Goal) expenseItem);
				}
				event.stopPropagation();
			}
		});
	}

	/**
	 * @param creditGoalEventHandler
	 *            the creditGoalEventHandler to set
	 */
	public void setCreditGoalEventHandler(
			final CreditGoalEventHandler creditGoalEventHandler) {
		this.creditGoalEventHandler = creditGoalEventHandler;
	}

}
